#-*- coding: utf-8 -*-

import os
import pickle

class Utils:
    
    def abspath(path):
	return os.path.normpath(os.path.join(os.getcwdu(), path))
    abspath = staticmethod(abspath)
    
    def replaceParams(_str, _dict):
	if not _str:
	    return ''
	if not len(_dict):
	    return ''
	for k in _dict.keys():
	    v = _dict[k]
	    _str = _str.replace('{'+k+'}', v)
	return _str
    replaceParams = staticmethod(replaceParams)

    def enum(*sequential, **named):
	enums = dict(zip(sequential, range(len(sequential))), **named)
	return type('Enum', (), enums)
    enum = staticmethod(enum)
    
    def getVar(dict_, key_, default_=None):
	return dict_[key_] if key_ in dict_ and dict_[key_] != None else default_
    getVar = staticmethod(getVar)
    
    def listsEq(list1, list2):
	if len(list1) != len(list2):
	    return False
	for item in list1:
	    if not item in list2:
		return False
	return True
    listsEq = staticmethod(listsEq)
    
    def loadSession(filename):
	if os.path.exists(filename) and os.path.isfile(filename):
	    sess = ""
	    try: 
		fd = open(filename, 'rU')
		sess = pickle.load(fd)
	    except Exception, e:
		pass
	    finally:
		fd.close()
	    return sess
	else:
	    return ""
    loadSession = staticmethod(loadSession)

    def saveSession(filename, what=""):
	try: 
	    fd = open(filename, 'w')
	    pickle.dump(what, fd)
	except Exception, e:
		raise Exception(e)
		pass
	finally:
	    fd.close()
    saveSession = staticmethod(saveSession)
    
    def cleanDir(path):
	if os.path.exists(path) and os.path.isdir(path):
	    files = os.listdir(path)
	    for f in files:
		file_path = path + '/' + f
		if os.path.isfile(file_path):
		    os.unlink(file_path)
    cleanDir = staticmethod(cleanDir)
    
    def decode(what):
	encs = ('utf-8', 'cp1251', 'cp1252', 'koi8r', 'ascii')
	for enc in encs:
	    try:
		unicode(what, enc,"strict")
	    except:
		pass
	    else:
		return unicode(what, enc,"strict")
	return what
    decode = staticmethod(decode)
    
